
package VisAVisTab;



import com.hp.hpl.jena.ontology.*;
import com.hp.hpl.jena.rdf.model.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;

import java.sql.*;

import java.util.*;

import edu.stanford.smi.protege.model.*;
import edu.stanford.smi.protege.util.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;


///////////////////////////////////////////////////////////////////////////////
// PostgresPanel

// PostgresPanel class encapsulates the GUI components that let the user
// connect to a data source and see the tables stored there

class PostgresPanel extends JPanel
        implements ActionListener, TreeSelectionListener, ItemListener,DragSourceListener, DragGestureListener,DropTargetListener {
    
    
    
    public PostgresPanel(OntologyPanel ontPanel) {
        
        
        // initialize
        this.ontPanel=ontPanel;
        queryPanel= new QueryPanelPostgres(this,ontPanel);
        
        tables = new Vector();
        
        // add UI components
        setLayout(new BorderLayout());
        
        GridBagLayout gridbag=new GridBagLayout();
        JPanel pNorth = new JPanel(gridbag);
        GridBagConstraints gbc=new GridBagConstraints();
        
        JLabel label1=new JLabel("Host IP");
        JLabel label2=new JLabel("Login");
        JLabel label3=new JLabel("Port");
        JLabel label4=new JLabel("Password");
        
        DropTarget dropTarget1=new DropTarget(txtHostIP,this);
        DropTarget dropTarget2=new DropTarget(txtPW,this);
        DropTarget dropTarget3=new DropTarget(txtUserID,this);
        DropTarget dropTarget4=new DropTarget(chooseDB,this);
        DropTarget dropTarget5=new DropTarget(txtPort,this);
        
        ontPanel.buildConstraints(gbc,0,0,1,1,100,100,GridBagConstraints.NONE);
        gridbag.setConstraints(label1,gbc);
        pNorth.add(label1);
        
        ontPanel.buildConstraints(gbc,1,0,1,1,100,100,GridBagConstraints.NONE);
        gridbag.setConstraints(txtHostIP,gbc);
        pNorth.add(txtHostIP);
        
        ontPanel.buildConstraints(gbc,2,0,1,1,100,100,GridBagConstraints.NONE);
        gridbag.setConstraints(label3,gbc);
        pNorth.add(label3);
        
        ontPanel.buildConstraints(gbc,3,0,1,1,100,100,GridBagConstraints.NONE);
        gridbag.setConstraints(txtPort,gbc);
        pNorth.add(txtPort);
        
        ontPanel.buildConstraints(gbc,0,1,1,1,100,100,GridBagConstraints.NONE);
        gridbag.setConstraints(label2,gbc);
        pNorth.add(label2);
        
        ontPanel.buildConstraints(gbc,1,1,1,1,100,100,GridBagConstraints.NONE);
        gridbag.setConstraints(txtUserID,gbc);
        pNorth.add(txtUserID);
        
        ontPanel.buildConstraints(gbc,2,1,1,1,100,100,GridBagConstraints.NONE);
        gridbag.setConstraints(label4,gbc);
        pNorth.add(label4);
        
        ontPanel.buildConstraints(gbc,3,1,1,1,100,100,GridBagConstraints.NONE);
        gridbag.setConstraints(txtPW,gbc);
        pNorth.add(txtPW);
        
        JLabel label5=new JLabel("Database");
        ontPanel.buildConstraints(gbc,4,0,1,1,100,100,GridBagConstraints.NONE);
        gridbag.setConstraints(label5,gbc);
        pNorth.add(label5);
        
        ontPanel.buildConstraints(gbc,5,0,1,1,100,100,GridBagConstraints.NONE);
        gridbag.setConstraints(chooseDB,gbc);
        pNorth.add(chooseDB);
        
        btnConnect.setMnemonic('C');
        btnConnect.addActionListener(this);
        ontPanel.buildConstraints(gbc,4,1,2,1,100,100,GridBagConstraints.NONE);
        gridbag.setConstraints(btnConnect,gbc);
        pNorth.add(btnConnect);
        
        
        add(pNorth,BorderLayout.NORTH);
        
        
        JPanel pCenter=new JPanel(gridbag);
        JPanel p6 = new JPanel(new BorderLayout());
        JPanel tableTypesPanel = new JPanel(new FlowLayout());
        allCheckBox = new JCheckBox("All");
        allCheckBox.setMnemonic('l');
        allCheckBox.addItemListener(this);
        tableTypesPanel.add(allCheckBox);
        sysCheckBox = new JCheckBox("System Table");
        sysCheckBox.setMnemonic('y');
        sysCheckBox.addItemListener(this);
        tableTypesPanel.add(sysCheckBox);
        tableCheckBox = new JCheckBox("Table");
        tableCheckBox.setMnemonic('t');
        tableCheckBox.addItemListener(this);
        tableTypesPanel.add(tableCheckBox);
        viewCheckBox = new JCheckBox("View");
        viewCheckBox.setMnemonic('V');
        viewCheckBox.addItemListener(this);
        tableTypesPanel.add(viewCheckBox);
        
        
        otherCheckBox = new JCheckBox("Other");
        otherCheckBox.setMnemonic('O');
        otherCheckBox.addItemListener(this);
        tableTypesPanel.add(otherCheckBox);
        p6.add(new LabeledComponent("Data Tables",tableTypesPanel,false),BorderLayout.NORTH);
        treeTables.setCellRenderer(new DBTreeCellRenderer());
        treeTables.setEditable(false);
        treeTables.setRootVisible(false);
        treeTables.setShowsRootHandles(true);
        treeTables.putClientProperty("JTree.lineStyle", "Angled");
        treeTables.addTreeSelectionListener(this);
        JPanel p7=new JPanel(new GridLayout(1,2));
        JScrollPane scrollPane = new JScrollPane(treeTables);
        scrollPane.setToolTipText("Drag a table or a column and drop it to the appropriate field to the right");
        
        scrollPane.setPreferredSize(new Dimension(250, 200));
        dragSource.addDragSourceListener(this);
        dragSource.createDefaultDragGestureRecognizer( treeTables, DnDConstants.ACTION_MOVE, this);
        
        p6.add(scrollPane,BorderLayout.CENTER);
        p7.add(p6);
        p7.add(queryPanel);
        
        ontPanel.buildConstraints(gbc,0,0,1,1,100,80,GridBagConstraints.BOTH);
        gridbag.setConstraints(p7,gbc);
        pCenter.add(p7);
        
        
        previewPanel=new DataPreviewPanel();
        ontPanel.buildConstraints(gbc,0,1,1,1,100,20,GridBagConstraints.BOTH);
        gridbag.setConstraints(previewPanel,gbc);
        pCenter.add(previewPanel);
        
        /*JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
        split.setTopComponent(p7);
        split.setBottomComponent(previewPanel);*/
        
        //split.setDividerLocation(-1000);
        //add(split,BorderLayout.CENTER);
        //add(previewPanel,BorderLayout.SOUTH);
        
        add(pCenter,BorderLayout.CENTER);
        
        connected = false;
        setConnectedGUI(false);
    }
    
    // Handle action events
    
    public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();
        if (source == btnConnect) {
            
            // reset data and GUI components
            boolean dbNotFound=false;
            queryPanel.tablesVector.removeAllElements();
            queryPanel.tableList.setListData(queryPanel.tablesVector);
            queryPanel.fieldsVector.removeAllElements();
            queryPanel.fieldInfoVector.removeAllElements();
            queryPanel.fieldList.setListData(queryPanel.fieldsVector);
            queryPanel.criteriaVector.removeAllElements();
            while (queryPanel.dm.getRowCount()!=0) queryPanel.dm.removeRow(0);
            foreignKeys.removeAllElements();
            
            //reset the data preview panel as well as the tree of the database
            previewPanel.deleteTable();
            tables.removeAllElements();
            rootNode = new DefaultMutableTreeNode(new TreeNodeInfo("Data Source",TreeNodeInfo.OTHER));
            treeModel = new DefaultTreeModel(rootNode);
            treeTables.setModel(treeModel);
            setConnectedGUI(false);
            
         
            //setup the connection
            String strURL="";
            try{
                databaseSelected =chooseDB.getText();
                strDriver="org.postgresql.Driver";
                strURL = "jdbc:postgresql://"+txtHostIP.getText()+":"+txtPort.getText()+"/"+databaseSelected;
                
                // load the JDBC driver
                Class.forName(strDriver);
                
                con = DriverManager.getConnection(strURL,
                        txtUserID.getText(), new String(txtPW.getPassword()));
                if (connectInfo == null)
                    connectInfo = new ConnectInfo(strDriver,strURL,txtUserID.getText(),new String(txtPW.getPassword()),"PostgreSQL");
                else
                    connectInfo.set(strDriver,strURL,txtUserID.getText(),new String(txtPW.getPassword()),"PostgreSQL");
                
                dsInfo = new DataSourceInfo(connectInfo);
                
                
                
            } catch (SQLException ex) {
                Global.defaultSQLExceptionHandler(JOptionPane.getFrameForComponent(this),ex);
                dbNotFound=true;
            } catch (Exception ex) {
            }
            
            
            //if the connection has been well established
            if (!dbNotFound){
                try{
                    DatabaseMetaData dbMetaData = con.getMetaData();
                    
                    
                    
                    // Obtain all the available table types from the data source
                    ResultSet rs = dbMetaData.getTableTypes();
                    Vector tableTypesVector = new Vector();
                    boolean more = rs.next();
                    while (more) {
                        String type = rs.getString("TABLE_TYPE");
                        tableTypesVector.addElement(type);
                        more = rs.next();
                    }
                    rs.close();
                    
                    int numTypes = tableTypesVector.size();
                    String[] tableTypes = new String[numTypes];
                    for (int i = 0; i < numTypes; i++)
                        tableTypes[i] = (String)tableTypesVector.get(i);
                    
                    // Set up the data tables tree
                    
                    ResultSet rsTables = dbMetaData.getTables(null,null,null,tableTypes);
                    
                    boolean bMore = rsTables.next();
                    while (bMore) {
                        
                        String strTableName = rsTables.getString("TABLE_NAME");
                        
                        
                        String tableTypeStr = rsTables.getString("TABLE_TYPE");
                        int tableType;
                        if (tableTypeStr.compareToIgnoreCase("SYSTEM TABLE") == 0)
                            tableType = TreeNodeInfo.TABLE_SYSTEM;
                        else if (tableTypeStr.compareToIgnoreCase("TABLE") == 0)
                            tableType = TreeNodeInfo.TABLE;
                        else if (tableTypeStr.compareToIgnoreCase("VIEW") == 0)
                            tableType = TreeNodeInfo.TABLE_VIEW;
                        else
                            tableType = TreeNodeInfo.TABLE_OTHER;
                        
                        // Get primary keys
                        
                        rs = dbMetaData.getPrimaryKeys(null,null,strTableName);
                        more = rs.next();
                        while (more) {
                            FieldInfo primary= new FieldInfo();
                            primary.fieldName=rs.getString("COLUMN_NAME");
                            primary.fieldParent=strTableName;
                            primaryKeys.add(primary);
                            more = rs.next();
                        }
                        rs.close();
                        
                        //Get foreign keys
                        
                        rs = dbMetaData.getImportedKeys(null,null,strTableName);
                        more = rs.next();
                        while (more) {
                            ForeignInfo foreign= new ForeignInfo(rs.getString("FKCOLUMN_NAME"),
                                    rs.getString("FKTABLE_NAME"),rs.getString("PKCOLUMN_NAME"),rs.getString("PKTABLE_NAME"));
                            foreignKeys.add(foreign);
                            more = rs.next();
                        }
                        rs.close();
                        
                        //add the table to the tree
                        TreeNodeInfo nodeInfo = new TreeNodeInfo(strTableName,tableType);
                        DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(nodeInfo);
                        treeModel.insertNodeInto(childNode, rootNode, rootNode.getChildCount());
                        treeTables.scrollPathToVisible(new TreePath(childNode.getPath()));
                        
                        //determine the data types of the columns of each table
                        ResultSet rsColumns = dbMetaData.getColumns(null,null,strTableName,null);
                        boolean bMore2 = rsColumns.next();
                        while (bMore2) {
                            String strColumnName = rsColumns.getString("COLUMN_NAME");
                            
                            
                            String strTypeName = rsColumns.getString("TYPE_NAME");
                            int sqlType = rsColumns.getShort("DATA_TYPE");
                            ValueType protegeType = Global.getSQLProtegeType(sqlType);
                            String nodeText = strColumnName+" ("+strTypeName+" --> "+protegeType.toString()+")";
                            boolean isPrimary=false;
                            
                            // Determine whether this column is a primary key
                            int colType = TreeNodeInfo.COLUMN;
                            for (int i = 0; i < primaryKeys.size(); i++) {
                                
                                String key = ((FieldInfo)primaryKeys.elementAt(i)).fieldName;
                                String keyTable = ((FieldInfo)primaryKeys.elementAt(i)).fieldParent;
                                if ((key.compareToIgnoreCase(strColumnName) == 0)&&(keyTable.compareToIgnoreCase(strTableName) == 0)){
                                    colType = TreeNodeInfo.COLUMN_PK;
                                    isPrimary=true;
                                    break;
                                }
                                
                            }
                            
                            // Determine whether this column is a foreign key
                            for (int i = 0; i < foreignKeys.size(); i++) {
                                String key = ((ForeignInfo)foreignKeys.elementAt(i)).fk_name;
                                String keyTable=((ForeignInfo)foreignKeys.elementAt(i)).fk_table;
                                if ((key.compareToIgnoreCase(strColumnName) == 0)&&(keyTable.compareToIgnoreCase(strTableName) == 0)) {
                                    if (!isPrimary) colType = TreeNodeInfo.COLUMN_FK;
                                    else colType=TreeNodeInfo.COLUMN_PFK;
                                    break;
                                }
                                
                            }
                            
                            //add each column to the tree under the table it belongs
                            TreeNodeInfo nodeInfo2 = new TreeNodeInfo(nodeText,colType);
                            DefaultMutableTreeNode childColumnNode = new DefaultMutableTreeNode(nodeInfo2);
                            treeModel.insertNodeInto(childColumnNode, childNode, childNode.getChildCount());
                            
                            bMore2 = rsColumns.next();
                        }
                        rsColumns.close();
                        
                        tables.add(nodeInfo);
                        
                        bMore = rsTables.next();
                    }

                    
                    rsTables.close();
                    
                    // Set the table type check boxes according to the types
                    // available in the data source
                    if (tables.size() == 0)
                        JOptionPane.showMessageDialog(JOptionPane.getFrameForComponent(this),"No table found in this data source.",Global.tabName,JOptionPane.INFORMATION_MESSAGE);
                    else {
                        setConnectedGUI(true);
                        connected = false;
                        allCheckBox.setEnabled(false);
                        sysCheckBox.setEnabled(false);
                        tableCheckBox.setEnabled(false);
                        viewCheckBox.setEnabled(false);
                        otherCheckBox.setEnabled(false);
                        for (int i = 0; i < tableTypes.length; i++) {
                            if (tableTypes[i].compareToIgnoreCase("SYSTEM TABLE") == 0) {
                                sysCheckBox.setEnabled(true);
                                sysCheckBox.setSelected(true);
                            } else if (tableTypes[i].compareToIgnoreCase("TABLE") == 0) {
                                tableCheckBox.setEnabled(true);
                                tableCheckBox.setSelected(true);
                            } else if (tableTypes[i].compareToIgnoreCase("VIEW") == 0) {
                                viewCheckBox.setEnabled(true);
                                viewCheckBox.setSelected(true);
                            } else {
                                otherCheckBox.setEnabled(true);
                                otherCheckBox.setSelected(true);
                            }
                        }
                        allCheckBox.setEnabled(true);
                        allCheckBox.setSelected(true);
                        connected = true;
                    }
                } catch (SQLException ex) {
                    Global.defaultSQLExceptionHandler(JOptionPane.getFrameForComponent(this),ex);
                } catch (Exception ex) {
                }
                
            }
            
        }
        
        
    }
    
    // Handle the state changes in the table type check boxes;
    // modify the table tree to show the appropriate tables
    
    public void itemStateChanged(ItemEvent e) {
        if (connected) {
            Object item = e.getItem();
            int newState = e.getStateChange();
            if (item == allCheckBox) {
                if (newState == ItemEvent.SELECTED) {
                    sysCheckBox.setSelected(true);
                    tableCheckBox.setSelected(true);
                    viewCheckBox.setSelected(true);
                    otherCheckBox.setSelected(true);
                }
            } else if (item == sysCheckBox) {
                if (newState == ItemEvent.DESELECTED) {
                    allCheckBox.setSelected(false);
                }
            } else if (item == tableCheckBox) {
                if (newState == ItemEvent.DESELECTED) {
                    allCheckBox.setSelected(false);
                }
            } else if (item == viewCheckBox) {
                if (newState == ItemEvent.DESELECTED) {
                    allCheckBox.setSelected(false);
                }
            } else if (item == otherCheckBox) {
                if (newState == ItemEvent.DESELECTED) {
                    allCheckBox.setSelected(false);
                }
            }
            
            Vector selectTypes = new Vector();
            if (sysCheckBox.isSelected())
                selectTypes.addElement("SYSTEM TABLE");
            if (tableCheckBox.isSelected())
                selectTypes.addElement("TABLE");
            if (viewCheckBox.isSelected())
                selectTypes.addElement("VIEW");
            if (otherCheckBox.isSelected()) {
                selectTypes.addElement("INDEX");
                selectTypes.addElement("SYSTEM INDEX");
                selectTypes.addElement("SYSTEM TOAST INDEX");
                selectTypes.addElement("SYSTEM VIEW");
            }
            
            int numTypes = selectTypes.size();
            String[] selectTableTypes = new String[numTypes];
            for (int i = 0; i < numTypes; i++)
                selectTableTypes[i] = (String)selectTypes.get(i);
            
            selectTableTypesForView(selectTableTypes);
        }
    }
    
    //implements the needed methods for interfaces used to handle Drag N Drop actions
    public void dragDropEnd(DragSourceDropEvent event) {
    }
    
    
    public void dragExit(DragSourceEvent event) {
        //System.out.println( "dragExit");
        
    }
    
    
    public void dropActionChanged( DragSourceDragEvent event) {
        //System.out.println( "dropActionChanged");
    }
    
    public void dragOver(DragSourceDragEvent event) {
        //System.out.println( "dragOver");
        
    }
    
    public void dragEnter(DragSourceDragEvent event) {
        //System.out.println( " dragEnter");
    }
    
    public void drop(DropTargetDropEvent event) {
        //reject drop actions for the upper connection fields
        if ((event.getDropTargetContext().getComponent()==chooseDB)||(event.getDropTargetContext().getComponent()==txtUserID)||
                (event.getDropTargetContext().getComponent()==txtPW)||(event.getDropTargetContext().getComponent()==txtPort)||
                (event.getDropTargetContext().getComponent()==txtHostIP)){
            event.rejectDrop();
        }
    }
    
    public void dragExit(DropTargetEvent event) {
        //System.out.println( "dragExit");
    }
    
    public void dropActionChanged( DropTargetDragEvent event ) {
    }
    
    public void dragOver(DropTargetDragEvent event) {
        // System.out.println( "dragOver");
    }
    public void dragEnter(DropTargetDragEvent event) {
        
        //System.out.println( "dragEnter");
        //event.acceptDrag (DnDConstants.ACTION_MOVE);
    }
    public void dragGestureRecognized( DragGestureEvent event) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode)treeTables.getLastSelectedPathComponent();
        if (node == null)
            return;
        Object selected = node.getUserObject();
        if ( selected != null ){
            StringSelection text = new StringSelection( selected.toString());
            
            // as the name suggests, starts the dragging
            dragSource.startDrag(event, DragSource.DefaultMoveDrop, text, this);
        } else {
            System.out.println( "nothing was selected");
        }
    }
    
    
    
    
    // Take a list of table types and modify the tree to show all the
    // tables of those types.
    
    private void selectTableTypesForView(String[] tableTypes) {
        // reset data and GUI components
        previewPanel.deleteTable();
        tables.removeAllElements();
        rootNode = new DefaultMutableTreeNode(new TreeNodeInfo("Data Source",TreeNodeInfo.OTHER));
        treeModel = new DefaultTreeModel(rootNode);
        treeTables.setModel(treeModel);
        
        try {
            // load the JDBC driver
            Class.forName(strDriver);
            
            Connection con = DriverManager.getConnection(connectInfo.m_DSN,
                    connectInfo.m_UID, connectInfo.m_PWD);
            
            DatabaseMetaData dbMetaData = con.getMetaData();
            ResultSet rsTables = dbMetaData.getTables(null,null,null,tableTypes);
            boolean bMore = rsTables.next();
            while (bMore) {
                String strTableName = rsTables.getString("TABLE_NAME");
                
                // Determine the table type
                String tableTypeStr = rsTables.getString("TABLE_TYPE");
                int tableType;
                if (tableTypeStr.compareToIgnoreCase("SYSTEM TABLE") == 0)
                    tableType = TreeNodeInfo.TABLE_SYSTEM;
                else if (tableTypeStr.compareToIgnoreCase("TABLE") == 0)
                    tableType = TreeNodeInfo.TABLE;
                else if (tableTypeStr.compareToIgnoreCase("VIEW") == 0)
                    tableType = TreeNodeInfo.TABLE_VIEW;
                else
                    tableType = TreeNodeInfo.TABLE_OTHER;
                
                // Get primary keys
                Vector primaryKeys = new Vector();
                
                ResultSet rs = dbMetaData.getPrimaryKeys(null,null,strTableName);
                boolean more = rs.next();
                while (more) {
                    primaryKeys.add(rs.getString("COLUMN_NAME"));
                    more = rs.next();
                }
                rs.close();
                
                //Get foreign keys
                rs = dbMetaData.getImportedKeys(null,null,strTableName);
                more = rs.next();
                while (more) {
                    ForeignInfo foreign= new ForeignInfo(rs.getString("FKCOLUMN_NAME"),
                            rs.getString("FKTABLE_NAME"),rs.getString("PKCOLUMN_NAME"),rs.getString("PKTABLE_NAME"));
                    foreignKeys.add(foreign);
                    more = rs.next();
                }
                rs.close();
                
                //reject drop actions for the upper connection fields
                TreeNodeInfo nodeInfo = new TreeNodeInfo(strTableName,tableType);
                DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(nodeInfo);
                treeModel.insertNodeInto(childNode, rootNode, rootNode.getChildCount());
                treeTables.scrollPathToVisible(new TreePath(childNode.getPath()));
                ResultSet rsColumns = dbMetaData.getColumns(null,null,strTableName,null);
                
                //determine the data types of each column
                boolean bMore2 = rsColumns.next();
                while (bMore2) {
                    String strColumnName = rsColumns.getString("COLUMN_NAME");
                    String strTypeName = rsColumns.getString("TYPE_NAME");
                    int sqlType = rsColumns.getShort("DATA_TYPE");
                    ValueType protegeType = Global.getSQLProtegeType(sqlType);
                    String nodeText = strColumnName+" ("+strTypeName+" --> "+protegeType.toString()+")";
                    
                    // Determine whether this column is a primary key
                    int colType = TreeNodeInfo.COLUMN;
                    for (int i = 0; i < primaryKeys.size(); i++) {
                        String key = (String)primaryKeys.elementAt(i);
                        if (key.compareToIgnoreCase(strColumnName) == 0) {
                            colType = TreeNodeInfo.COLUMN_PK;
                            break;
                        }
                    }
                    
                    // Determine whether this column is a foreign key
                    for (int i = 0; i < foreignKeys.size(); i++) {
                        String key = ((ForeignInfo)foreignKeys.elementAt(i)).fk_name;
                        if (key.compareToIgnoreCase(strColumnName) == 0) {
                            colType = TreeNodeInfo.COLUMN_FK;
                            break;
                        }
                        
                    }
                    
                    //add each column to the tree under the table it belongs
                    TreeNodeInfo nodeInfo2 = new TreeNodeInfo(nodeText,colType);
                    DefaultMutableTreeNode childColumnNode = new DefaultMutableTreeNode(nodeInfo2);
                    treeModel.insertNodeInto(childColumnNode, childNode, childNode.getChildCount());
                    
                    bMore2 = rsColumns.next();
                }
                rsColumns.close();
                
                tables.add(nodeInfo);
                
                bMore = rsTables.next();
            }
            
            rsTables.close();
            con.close();
            
            if (tables.size() == 0) {
                JOptionPane.showMessageDialog(JOptionPane.getFrameForComponent(this),"No table of the selected types above found.",Global.tabName,JOptionPane.INFORMATION_MESSAGE);
            }
        } catch (SQLException ex) {
            Global.defaultSQLExceptionHandler(JOptionPane.getFrameForComponent(this),ex);
        } catch (Exception ex) {
        }
    }
    
    // This method is used to enable/disable the GUI components based
    // on the current state of the tab widget
    
    private void setConnectedGUI(boolean isConnected) {
        connected = isConnected;
        
        allCheckBox.setEnabled(isConnected);
        sysCheckBox.setEnabled(isConnected);
        tableCheckBox.setEnabled(isConnected);
        viewCheckBox.setEnabled(isConnected);
        otherCheckBox.setEnabled(isConnected);
        
        if (!isConnected) {
            allCheckBox.setSelected(isConnected);
            sysCheckBox.setSelected(isConnected);
            tableCheckBox.setSelected(isConnected);
            viewCheckBox.setSelected(isConnected);
            otherCheckBox.setSelected(isConnected);
        }
        
    }
    
    // A new table has been selected from the tree and we want to display
    // a preview of it in the preview table
    
    public void valueChanged(TreeSelectionEvent e) {
        if (treeModel.getChildCount(treeModel.getRoot())!=0){
            DefaultMutableTreeNode node = (DefaultMutableTreeNode)treeTables.getLastSelectedPathComponent();
            if (node!=null){
                DefaultMutableTreeNode parentNode=(DefaultMutableTreeNode)node.getParent();
                TreeNodeInfo parentName=(TreeNodeInfo)parentNode.getUserObject();
                if (parentName.toString().equals("Data Source")){
                    TreeNodeInfo nodeInfo = (TreeNodeInfo)node.getUserObject();
        
                    String strQuery = "SELECT * FROM " + nodeInfo.m_text;
                    previewPanel.updateTable(connectInfo,strQuery,null);
                    }
                }
            if (node == null)
                return;
        }
    }
    
    
    
    
    
    private JCheckBox allCheckBox, sysCheckBox, tableCheckBox, viewCheckBox, otherCheckBox;
    private String[] tableTypes;
    
    private Vector tables;
    
    private String strDriver;
    
    
    private JTextField chooseDB = new JTextField(15);
    private JTextField txtHostIP = new JTextField("127.0.0.1",15);
    private JTextField txtPort = new JTextField("5432",4);
    private JTextField txtUserID = new JTextField(15);
    private JPasswordField txtPW = new JPasswordField(15);
    private JButton btnConnect = new JButton("Connect");
    QueryPanelPostgres queryPanel ;
    OntologyPanel ontPanel;
    Connection con;
    String databaseSelected;
    
    Vector primaryKeys = new Vector();
    Vector foreignKeys = new Vector();
    DragSource dragSource=new DragSource();
    
    private boolean connected = false;
    
    ConnectInfo connectInfo = null;
    
    private DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(new TreeNodeInfo("Data Source",TreeNodeInfo.OTHER));
    DefaultTreeModel treeModel = new DefaultTreeModel(rootNode);
    JTree treeTables = new JTree(treeModel);
    
    private DataPreviewPanel previewPanel;
    private DataSourceInfo dsInfo;
}


/*A class that describes a node of a JTree
 */
class TreeNodeInfo extends Object {
    
    public TreeNodeInfo(String text, int type) {
        m_text = text;
        m_type = type;
    }
    
    public TreeNodeInfo(String text, int type, int sqlType) {
        m_text = text;
        m_type = type;
        m_colSQLType = sqlType;
    }
    
    public String toString() {
        return m_text;
    }
    
    public String m_text;
    public int m_type;
    public int m_colSQLType;
    
    public static final int TABLE_SYSTEM = 1;
    public static final int TABLE = 2;
    public static final int TABLE_VIEW = 3;
    public static final int TABLE_OTHER = 10;
    
    public static final int COLUMN = 100;
    public static final int COLUMN_PK = 101;
    public static final int COLUMN_FK = 102;
    public static final int COLUMN_PFK = 103;
    
    public static final int OTHER = -1;
}

//a class containing information about the database supports
class DataSourceInfo extends Object {
    
    public DataSourceInfo(ConnectInfo connectInfo) {
        m_connectInfo = connectInfo;
        
        try {
            Class.forName(m_connectInfo.m_driver);
            
            Connection con = DriverManager.getConnection(m_connectInfo.m_DSN,
                    m_connectInfo.m_UID, m_connectInfo.m_PWD);
            
            DatabaseMetaData dbmd = con.getMetaData();
            
            m_supportsANSI92EntryLevelSQL = dbmd.supportsANSI92EntryLevelSQL();
            m_supportsANSI92FullSQL = dbmd.supportsANSI92FullSQL();
            m_supportsANSI92IntermediateSQL = dbmd.supportsANSI92IntermediateSQL();
            m_supportsCoreSQLGrammar = dbmd.supportsCoreSQLGrammar();
            
            con.close();
        } catch (SQLException ex) {
            String exceptionString = "Message:  " + ex.getMessage();
            
            JOptionPane.showMessageDialog(null,exceptionString,"Database Connection Problem",JOptionPane.ERROR_MESSAGE);
            ex = ex.getNextException();
        } catch (Exception ex) {
        }
    }
    
    public boolean m_supportsANSI92EntryLevelSQL;
    public boolean m_supportsANSI92FullSQL;
    public boolean m_supportsANSI92IntermediateSQL;
    public boolean m_supportsCoreSQLGrammar;
    
    private ConnectInfo m_connectInfo;
}


//a class containing all the information needed about a foreign key
class ForeignInfo{
    
    public ForeignInfo(String fk_name,String fk_table,String pk_name,String pk_table){
        this.fk_name=fk_name;
        this.fk_table=fk_table;
        this.pk_name=pk_name;
        this.pk_table=pk_table;
    }
    
    String fk_name;
    String fk_table;
    String pk_name;
    String pk_table;
}


